<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <base href="<%=basePath%>"/>
    <title>茶叶进销存系统 - 采购管理</title>
    <link rel="stylesheet" href="css/global.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
</head>
<body>
<div class="app-container">
    <!-- 侧边栏 -->
    <div class="sidebar" id="sidebar">
        <div class="sidebar-logo" onclick="toggleSidebar()">
            <span><i class="fas fa-leaf tea-icon"></i> 茶叶进销存系统</span>
        </div>

        <div class="sidebar-menu">
            <div
                    class="menu-item "
                    onclick="location.href='views/home.jsp'"
            >
                <i class="fas fa-home"></i>
                <span>系统首页</span>
            </div>
            <div class="menu-item" onclick="location.href='TeaServlet'">
                <i class="fas fa-coffee"></i>
                <span>茶叶管理</span>
            </div>
            <div class="menu-item" onclick="location.href='CategoryServlet'">
                <i class="fas fa-tags"></i>
                <span>分类管理</span>
            </div>
            <div class="menu-item" onclick="location.href='WarehouseServlet'">
                <i class="fas fa-boxes"></i>
                <span>仓库管理</span>
            </div>
            <div class="menu-item" onclick="location.href='OrderServlet'">
                <i class="fas fa-receipt"></i>
                <span>订单管理</span>
            </div>
            <div class="menu-item" onclick="location.href='LogisticsServlet'">
                <i class="fas fa-shipping-fast"></i>
                <span>物流管理</span>
            </div>
            <div class="menu-item" onclick="location.href='SupplierServlet'">
                <i class="fas fa-truck"></i>
                <span>供应商管理</span>
            </div>
            <div class="menu-item active" onclick="location.href='<%=basePath%>purchase/list'">
                <i class="fas fa-truck"></i>
                <span>采购管理</span>
            </div>
            <div class="menu-item" onclick="location.href='CustomerServlet'">
                <i class="fas fa-users"></i>
                <span>客户管理</span>
            </div>
            <div class="menu-item" onclick="location.href='AddressServlet'">
                <i class="fas fa-map-marker-alt"></i>
                <span>地址管理</span>
            </div>
        </div>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
        <!-- 顶部导航栏 -->
        <div class="navbar">
            <div class="navbar-left">
                <h3><i class="fas fa-shopping-cart tea-icon"></i> 采购管理</h3>
            </div>
            <div class="navbar-right">
                <span><i class="fas fa-user tea-icon"></i> 欢迎，${ username}管理员</span>
                <a href="LogoutServlet" class="el-link el-link--danger ml-10"><i class="fas fa-sign-out-alt"></i> 退出</a>
            </div>
        </div>

        <!-- 内容卡片 -->
        <div class="el-card fade-in">
            <div class="el-card__header">
                <span><i class="fas fa-list tea-icon"></i> 采购单列表</span>
                <div>
                    <input type="text" value="${searchKeyword}" class="el-input__inner" placeholder="请输入采购单号或供应商名称" id="searchKeyword" style="width: 250px;">
                    <select class="el-input__inner" id="statusFilter" style="width: 150px; margin-left: 10px;">
                        <option value="">全部状态</option>
                        <option value="0" ${selectedStatus == '0' ? 'selected' : ''}>待审核</option>
                        <option value="1" ${selectedStatus == '1' ? 'selected' : ''}>已审核</option>
                        <option value="2" ${selectedStatus == '2' ? 'selected' : ''}>已入库</option>
                        <option value="3" ${selectedStatus == '3' ? 'selected' : ''}>已完成</option>
                        <option value="4" ${selectedStatus == '4' ? 'selected' : ''}>已取消</option>
                    </select>
                    <button class="el-button el-button--primary" onclick="searchPurchase()" style="margin-left: 10px;">
                        <i class="fas fa-search"></i> 搜索
                    </button>
                    <button class="el-button el-button--success" onclick="location.href='purchase/add'" style="margin-left: 10px;">
                        <i class="fas fa-plus"></i> 新增采购单
                    </button>
                </div>
            </div>
            <div class="el-card__body">
                <c:choose>
                    <c:when test="${not empty purchaseList}">
                        <table class="el-table">
                            <thead>
                            <tr>
                                <th>编号</th>
                                <th>采购单号</th>
                                <th>供应商</th>
                                <th>仓库</th>
                                <th>采购金额</th>
                                <th>状态</th>
                                <th>操作</th>
                            </tr>
                            </thead>
                            <tbody>
                            <c:forEach items="${purchaseList}" var="purchase">
                                <tr>
                                    <td class="cell">${purchase.purchase_id}</td>
                                    <td class="cell">
                                        <strong style="color: var(--primary-color);">${purchase.purchase_no}</strong>
                                    </td>
                                    <td class="cell">${purchase.supplier.supplier_name}</td>
                                    <td class="cell">${purchase.warehouse.warehouse_name}</td>
                                    <td class="cell">
                                        <span style="color: var(--success-color); font-weight: bold;">
                                            ¥<fmt:formatNumber value="${purchase.total_amount}" pattern="#,##0.00"/>
                                        </span>
                                    </td>
                                    <td class="cell">
                                        <c:choose>
                                            <c:when test="${purchase.status == 0}">
                                                <span class="el-tag el-tag--warning">待审核</span>
                                            </c:when>
                                            <c:when test="${purchase.status == 1}">
                                                <span class="el-tag el-tag--info">已审核</span>
                                            </c:when>
                                            <c:when test="${purchase.status == 2}">
                                                <span class="el-tag el-tag--primary">已入库</span>
                                            </c:when>
                                            <c:when test="${purchase.status == 3}">
                                                <span class="el-tag el-tag--success">已完成</span>
                                            </c:when>
                                            <c:otherwise>
                                                <span class="el-tag el-tag--danger">已取消</span>
                                            </c:otherwise>
                                        </c:choose>
                                    </td>
                                    <td class="cell">
                                        <div class="action-links">
                                            <a href="purchase/detail?id=${purchase.purchase_id}" class="el-link el-link--info">
                                                <i class="fas fa-eye"></i> 查看
                                            </a>
                                            <c:if test="${purchase.status == 0}">
                                                <a href="purchase/edit?id=${purchase.purchase_id}" class="el-link el-link--primary">
                                                    <i class="fas fa-edit"></i> 编辑
                                                </a>
                                                <a href="javascript:void(0)" onclick="deletePurchase(${purchase.purchase_id})" class="el-link el-link--danger">
                                                    <i class="fas fa-trash"></i> 删除
                                                </a>
                                            </c:if>
                                        </div>
                                    </td>
                                </tr>
                            </c:forEach>
                            </tbody>
                        </table>

                        <div class="el-pagination mt-20">
                            <div style="display: flex; align-items: center; justify-content: space-between;">
                                <!-- 每页显示条数选择 (左侧) -->
                                <div style="display: flex; align-items: center;">
                                    <span style="margin-right: 10px;">每页显示：</span>
                                    <select class="el-input__inner" id="pageSizeSelect" style="width: 80px; height: 35px"
                                            onchange="changePageSize(this.value)">
                                        <option value="5" ${param.pageSize == '5' ? 'selected' : ''}>5</option>
                                        <option value="10" ${param.pageSize == '10' ? 'selected' : ''}>10</option>
                                        <option value="20" ${param.pageSize == '20' ? 'selected' : ''}>20</option>
                                        <option value="50" ${param.pageSize == '50' ? 'selected' : ''}>50</option>
                                    </select>
                                    <span style="margin-left: 10px;">条</span>
                                </div>

                                <!-- 分页导航 (右侧) -->
                                <ul style="display: flex; list-style: none; margin: 0; padding: 0;">
                                    <!-- 第一页 -->
                                    <c:if test="${currentPage > 1}">
                                        <li>
                                            <a href="purchase/list?page=1&status=${selectedStatus}&search=${searchKeyword}&pageSize=${pageSize}"
                                               class="page-link" title="第一页">««</a>
                                        </li>
                                    </c:if>

                                    <!-- 上一页 -->
                                    <c:if test="${currentPage > 1}">
                                        <li>
                                            <a href="purchase/list?page=${currentPage-1}&status=${selectedStatus}&search=${searchKeyword}&pageSize=${pageSize}"
                                               class="page-link" title="上一页">&laquo;</a>
                                        </li>
                                    </c:if>

                                    <!-- 页码 -->
                                    <c:forEach begin="1" end="${totalPages}" var="i">
                                        <c:if test="${i == 1 || i == totalPages || (i >= currentPage-2 && i <= currentPage+2)}">
                                            <li>
                                                <a href="purchase/list?page=${i}&status=${selectedStatus}&search=${searchKeyword}&pageSize=${pageSize}"
                                                   class="page-link ${i == currentPage ? 'active' : ''}">${i}</a>
                                            </li>
                                        </c:if>
                                        <c:if test="${i == currentPage-3 || i == currentPage+3}">
                                            <li><span class="page-ellipsis">...</span></li>
                                        </c:if>
                                    </c:forEach>

                                    <!-- 下一页 -->
                                    <c:if test="${currentPage < totalPages}">
                                        <li>
                                            <a href="purchase/list?page=${currentPage+1}&status=${selectedStatus}&search=${searchKeyword}&pageSize=${pageSize}"
                                               class="page-link" title="下一页">&raquo;</a>
                                        </li>
                                    </c:if>

                                    <!-- 最后一页 -->
                                    <c:if test="${currentPage < totalPages}">
                                        <li>
                                            <a href="purchase/list?page=${totalPages}&status=${selectedStatus}&search=${searchKeyword}&pageSize=${pageSize}"
                                               class="page-link" title="最后一页">»»</a>
                                        </li>
                                    </c:if>
                                </ul>
                            </div>
                        </div>
                    </c:when>
                    <c:otherwise>
                        <div style="text-align: center; padding: 60px 0; color: var(--text-secondary);">
                            <i class="fas fa-inbox" style="font-size: 48px; margin-bottom: 20px; opacity: 0.5;"></i>
                            <h4>暂无采购单数据</h4>
                            <p>点击上方"新增采购单"按钮创建第一个采购单</p>
                        </div>
                    </c:otherwise>
                </c:choose>
            </div>
        </div>
    </div>
</div>

<script>
    function deletePurchase(id) {
        if (confirm('确定要删除这个采购单吗？删除后不可恢复！')) {
            location.href = 'purchase/delete?id=' + id;
        }
    }

    function searchPurchase() {
        const searchKeyword = document.getElementById('searchKeyword').value;
        const status = document.getElementById('statusFilter').value;
        let url = "purchase/list?";
        if (searchKeyword) url += "search=" + encodeURIComponent(searchKeyword) + "&";
        if (status) url += "status=" + encodeURIComponent(status) + "&";
        location.href = url;
    }

    function changePageSize(size) {
        const searchKeyword = document.getElementById('searchKeyword').value;
        const status = document.getElementById('statusFilter').value;
        let url = "purchase/list?pageSize=" + size + "&page=1&";
        if (searchKeyword) url += "search=" + encodeURIComponent(searchKeyword) + "&";
        if (status) url += "status=" + encodeURIComponent(status) + "&";
        location.href = url;
    }

    let isCollapsed = false;

    function toggleSidebar() {
        const sidebar = document.getElementById('sidebar');
        isCollapsed = !isCollapsed;
        sidebar.classList.toggle('collapsed', isCollapsed);
        localStorage.setItem('sidebarCollapsed', isCollapsed);
    }

    window.onload = function() {
        const savedState = localStorage.getItem('sidebarCollapsed') === 'true';
        if(savedState) {
            document.getElementById('sidebar').classList.add('collapsed');
            isCollapsed = true;
        }
        document.getElementById("pageSizeSelect").value = "${param.pageSize}" || "10";

        // 显示成功/错误消息
        const urlParams = new URLSearchParams(window.location.search);
        if (urlParams.get('success')) {
            const success = urlParams.get('success');
            switch(success) {
                case 'add':
                    alert('采购单创建成功！');
                    break;
                case 'update':
                    alert('采购单修改成功！');
                    break;
                case 'delete':
                    alert('采购单删除成功！');
                    break;
                default:
                    alert('操作成功！');
            }
        } else if (urlParams.get('error')) {
            const error = urlParams.get('error');
            switch(error) {
                case 'no_items':
                    alert('请至少添加一个采购项目');
                    break;
                case 'save_failed':
                    alert('保存失败，请重试');
                    break;
                case 'update_failed':
                    alert('修改失败，请重试');
                    break;
                case 'delete_failed':
                    alert('删除失败，请重试');
                    break;
                case 'not_found':
                    alert('采购单不存在');
                    break;
                case 'cannot_edit':
                    alert('该采购单状态不允许编辑');
                    break;
                case 'cannot_delete':
                    alert('该采购单状态不允许删除');
                    break;
                case 'invalid_id':
                    alert('无效的采购单ID');
                    break;
                case 'system_error':
                    alert('系统错误，请重试');
                    break;
                default:
                    alert('操作失败，请重试');
            }
        }
    }
</script>
</body>
</html>
